package co.fitstart.weapp.api.web.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.weapp.api.handler.SmsSender;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private SmsSender smsSender;

    /**
     * 
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult sendVerifyCode(@RequestParam("mobile") String mobile) {
        HttpResult httpResult = new HttpResult();
        
        try {
            if(org.apache.commons.lang3.StringUtils.isNotBlank(mobile)) {
                mobile = mobile.replace(" ", "");
                
                // Generate random code in 6 digits
                String code = smsSender.generateVerifyCode(mobile.trim());
                boolean send = smsSender.sendVerifyCode(mobile, code);
                
                if(send) {
                    String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "fitstart"));
                    logger.info("send sms message mobile [{}] token [{}] code [{}]", mobile, token, code);
                    httpResult.success()
                              .data("token", token)
                              .message("发送验证码成功");
                } else {
                    logger.error("#sendVerifyCode() faild with response [{}]", JsonUtils.toJson(httpResult));
                    httpResult.fail("501").message("发送验证码失败");
                }
            } else {
                httpResult.fail("1").message("请输入手机号");
            }
        } catch (Exception e) {
            logger.error("#sendVerifyCode() occurs error", e);
            httpResult.fail("500").message("发送验证码请求失败");
        }
        
        return httpResult;
    }
}
